<?php
/**
 * 系统钩子类
 * @author andery <andery@foxmail.com>
 * @link http://www.Nimo.com/
 * @version $Id: CConf.php 2010-07-17 23:02:22Z andery $
 */
class CHooks
{
    private $_enabled = false;
    private $_hooks = array();
    private static $_instance = null;
    
    /**
     * 构造函数初始化
     */
    private function __construct()
    {
        $this->_enabled = CConf::get('system.hooks_enabled');
        if (!$this->_enabled) {
            return;
        }
        $hooks = @include_once(CConf::get('system.hooks'));
        if ($hooks=='' || !is_array($hooks)) {
            return;
        }
        $this->_hooks = $hooks;
    }
    
    /**
     * 单例模式
     */
    public static function getInstance()
    {     
        if (self::$_instance == null) {
            self::$_instance = new CHooks();
        } else {
            return self::$_instance;
        }
    }
    
    /**
     * 调用钩子
     */
    public function call_hook($hook_name)
    {
        if (!$this->_enabled || !isset($this->_hooks[$hook_name])) {
			return false;
		}
		// 一个钩子对应多个插件
		if (isset($this->_hooks[$hook_name][0]) && is_array($this->_hooks[$hook_name][0])) {
			foreach ($this->_hooks[$hook_name] as $val) {
				$this->_run_hook($val);
			}
		} else {
			$this->_run_hook($this->_hooks[$hook_name]);
		}
    }
    
    /**
     * 运行挂载函数
     */
    private function _run_hook($data)
    {
        if ((!isset($data['class']) && !isset($data['function'])) || !isset($data['file'])) {
            return false;
        }
        if ($data['class']=='' && $data['function']=='') {
            return false;
        }
        $hook_file = Nimo::app()->getAppPath() . $data['file'];
        if (!is_file($hook_file)) {
            return false;
        }
        if ($data['class']!='') {
            if (!class_exists($data['class'])) {
                include_once($hook_file);
            }
            $hook = new $data['class'];
			$hook->$data['function']($data['params']);
        } else {
            if ( ! function_exists($data['function'])) {
				include_once($hook_file);
			}
			$data['function']($data['params']);
        }
    }
    
    public function __clone(){}
}